<template>
  <div class="wd-upload">
    <el-upload
        :class="{ hide: disabled }"
        v-model="files"
        :accept="accept"
        :before-upload="beforeUpload"
        :file-list="files"
        :http-request="httpRequest"
        :limit="limit"
        :on-exceed="onExceed"
        action=""
        listType="picture-card"
        multiple
        :disabled="disabled"
    >
      <i class="el-icon-plus"></i>
      <div
          slot="file"
          slot-scope="{ file }"
          v-if="file"
          class="wd-upload-item"
          :title="file.title"
      >
        <img v-if="isFiles" class="wd-files" src="@/assets/img/word.png" alt/>
        <img v-else class="wd-thumb" :src="$serverUrl(file.url)" alt/>
        <span class="wd-title">{{ file.title }}</span>
        <span class="wd-actions" v-if="file">
          <span v-if="!isFiles" @click="onPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <a
              v-if="!readonly"
              :href="$serverUrl(file.url)"
              :download="file.title"
              target="_self"
          >
            <i class="el-icon-download"></i>
          </a>
          <span v-if="!readonly" @click="onRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog append-to-body :visible.sync="preview">
      <img width="100%" :src="$serverUrl(previewUrl)" alt=""/>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, watch, onMounted, defineProps, defineEmits} from 'vue';
// import { UploadImage } from "@/api/api";
// import { UploadFile } from "@/api/newApi";
import {postFile} from "@/utils/http";

// Props
const props = defineProps({
  max: {
    type: Number,
    default: 200,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: "images",
  },
  value: {
    type: Array,
    default: () => [],
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  limit: {
    type: Number,
    default: 10,
  },
});

// Reactive state
const files = ref([]);
const preview = ref(false);
const previewUrl = ref("");
const _files = "files";
const _images = "images";

// Computed properties
const isFiles = computed(() => props.type === _files);
const accept = computed(() => isFiles.value ? ".doc,.docx,.xls,.xlsx,.pdf" : ".jpeg,.jpg,.png");
const url = computed(() => isFiles.value ? UploadFile : UploadImage);

// Watchers
watch(
    () => props.value,
    (newVal) => {
      get();
    }
)
// Methods
const get = () => {
  files.value = props.value
      ? props.value.map((e) => {
        if (isFiles.value) {
          return {
            name: e.fileName,
            title: e.fileTitle,
            type: e.fileExp,
            url: e.fileUrl,
          };
        } else {
          const title = e.imgUrl
              ? "预习报告" + e.imgUrl.substr(e.imgUrl.lastIndexOf("."))
              : "";
          return {
            title,
            url: e.imgUrl,
          };
        }
      })
      : [];
};

const set = () => {
  const emit = defineEmits();
  emit("input", files.value.map((e) => {
    return isFiles.value
        ? {
          fileTitle: e.title,
          fileName: e.name,
          fileExp: e.type,
          fileUrl: e.url,
        }
        : {
          imgUrl: e.url,
        };
  }));
};

const beforeUpload = (file) => {
  return props.$checkFile(file, accept.value, props.max);
};

const onExceed = () => {
  props.$messageWarning(`最多上传 ${props.limit} 个文件`);
};

const onPreview = (file) => {
  if (file && file.url) {
    previewUrl.value = file.url;
    preview.value = true;
  }
};

const onRemove = (file) => {
  props.$messageConfirm(`是否要删除 ${file.title} ？`, () => {
    const index = files.value.findIndex(f => f.url === file.url);
    if (index !== -1) {
      files.value.splice(index, 1);
      set();
    }
  });
};

const httpRequest = (item) => {
  if (item && item.file) {
    postFile(url.value, item.file)
        .then((file) => {
          if (file) {
            files.value.push(file);
            set();
            props.$messageSuccess("上传成功");
          } else {
            props.$messageError("未返回文件信息");
          }
        })
        .catch((err) => {
          props.$messageError(err);
        });
  }
};

onMounted(() => {
  get();
});
</script>

<style>
.hide .el-upload--picture-card {
  display: none !important;
}
</style>
